package com.sun.gulimall.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author lk
 * @version 1.0.0
 * @Description LoginController
 * @createTime 2024/2/11 16:51
 */
@Controller
public class LoginController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 查询用户信息
     * @param token 令牌
     * @return
     */
    @ResponseBody
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam(value = "token") String token){
        return redisTemplate.opsForValue().get(token);
    }


    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url")String url, Model model, @CookieValue(value = "sso_token",required = false)String sso_token){
        if(!StringUtils.isEmpty(sso_token)){
            return "redirect:"+ url + "?token="+sso_token;
        }
        //编写一个隐藏的input框，用于存储调回的url
        model.addAttribute("url",url);
        return "login";
    }

    /***
     * 处理登录请求
     * @param username
     * @param password
     * @param url
     * @param response
     * @return
     */
    @PostMapping(value = "/doLogin")
    public String doLogin(@RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("redirect_url") String url, HttpServletResponse response) {
        //登录成功跳转，跳回到登录页
        if(!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)){
            //登录成功保存用户信息并传递token
            String token = UUID.randomUUID().toString().replace("_", "");
            redisTemplate.opsForValue().set(token, username);
            //给浏览器留下登录过的痕迹
            //实现一次登录，处处登录的核心就是认证通过之后给浏览器留下一个痕迹，凡是访ssoserver.com这个域名的都会带上这个痕迹，通过使用cookie实现
            Cookie sso_token = new Cookie("sso_token",token);
            response.addCookie(sso_token);
            return "redirect:" + url + "?token="+token;
        }
        return "login";
    }
}
